import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            //第一个数去重
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            for (int j = nums.length - 1; j > i; j--) {

                // 第二个数去重
                if (j < nums.length - 1 && nums[j] == nums[j + 1]) continue;

                int left = i + 1, rigth = j - 1;
                while (left < rigth) {

                    long sum = (long) nums[i] + nums[left] + nums[rigth] + nums[j];
                    if (sum > (long)target) rigth--;
                    else if (sum < (long)target) left++;
                    else {
                        res.add(Arrays.asList(nums[i], nums[left], nums[rigth], nums[j]));
                        while (left < rigth && nums[left] == nums[left + 1]) left++;
                        while (left < rigth && nums[rigth] == nums[rigth - 1]) rigth--;
                        left++;
                        rigth--;
                    }
                }
            }
        }
        return res;
    }
}